package com.fnzn.entranceGuard.rest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;
import java.util.UUID;

import com.fnzn.entranceGuard.entity.InitialQrManage;
import com.fnzn.entranceGuard.service.IInitialQrManageService;
import com.fnzn.entranceGuard.util.AjaxJson;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import com.github.pig.common.constant.CommonConstant;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.common.util.Query;
import com.github.pig.common.util.R;
import com.github.pig.common.web.BaseController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 初始二维码管理 前端控制器
 * </p>
 *
 * @author JokerGao
 * @since 2018-06-29
 */
@RestController
@RequestMapping("/initialQrManage")
public class InitialQrManageController extends BaseController {
    @Autowired private IInitialQrManageService initialQrManageService;

    /**
    * 通过ID查询
    *
    * @param id ID
    * @return InitialQrManage
    */
    @GetMapping("/{id}")
    public R<InitialQrManage> get(@PathVariable Integer id) {
        return new R<>(initialQrManageService.selectById(id));
    }


    /**
    * 分页查询信息
    *
    * @param params 分页对象
    * @return 分页对象
    */
    @RequestMapping("/page")
    public Page page(@RequestParam Map<String, Object> params, InitialQrManage initialQrManage) {
        Page<InitialQrManage> page = new Page<InitialQrManage>(Integer.parseInt(params.getOrDefault("page", 1).toString())
                , Integer.parseInt(params.getOrDefault("limit", 10).toString()));
        EntityWrapper entityWrapper = new EntityWrapper<>();
        entityWrapper.eq(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
        if(StringUtils.isNotEmpty(initialQrManage.getType())) {
            entityWrapper.eq("type",initialQrManage.getType());
        }
        if(StringUtils.isNotEmpty(initialQrManage.getCommunityId())) {
            entityWrapper.eq("community_id",initialQrManage.getCommunityId());
        }
        if(StringUtils.isNotEmpty(initialQrManage.getBuildingId())) {
            entityWrapper.eq("building_id",initialQrManage.getBuildingId());
        }
        if(StringUtils.isNotEmpty(initialQrManage.getUnitId())) {
            entityWrapper.eq("unit_id",initialQrManage.getUnitId());
        }
        entityWrapper.orderBy("create_time",false);
        entityWrapper.setSqlSelect("id, type, img_path AS imgPath, community_id AS communityId, (select name from community_info where id = community_id ) as communityName, building_id AS buildingId, (select building_name from community_building where id = building_id ) as buildingName, unit_id AS unitId, (select unit_name from building_unit where id = unit_id ) as unitName, create_user AS createUser, create_time AS createTime, update_user AS updateUser, update_time AS updateTime, del_flag AS delFlag, var1, var2");
        //return initialQrManageService.selectPage(new Query<>(params), entityWrapper);
        return initialQrManageService.selectPage(page, entityWrapper);
    }

    /**
     * 添加
     * @param  initialQrManage  实体
     * @return success/false
     */
    @PostMapping
    public R<Boolean> add(@RequestBody InitialQrManage initialQrManage) {
        initialQrManage.setDelFlag(CommonConstant.STATUS_NORMAL);
        initialQrManage.setCreateUser(getUserName());
        return new R<>(initialQrManageService.insert(initialQrManage));
    }

    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable String id) {
        InitialQrManage initialQrManage = new InitialQrManage();
        initialQrManage.setId(id);
        initialQrManage.setUpdateUser(getUserName());
        initialQrManage.setUpdateTime(new Date());
        initialQrManage.setDelFlag(CommonConstant.STATUS_DEL);
        return new R<>(initialQrManageService.updateById(initialQrManage));
    }

    /**
     * 编辑
     * @param  initialQrManage  实体
     * @return success/false
     */
    @PutMapping
    public R<Boolean> edit(@RequestBody InitialQrManage initialQrManage) {
        initialQrManage.setUpdateUser(getUserName());
        initialQrManage.setUpdateTime(new Date());
        return new R<>(initialQrManageService.updateById(initialQrManage));
    }

    /**
     * 上传图片保存本地
     * @param modelMap
     * @param request
     * @param type
     * @param path
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload")
    public AjaxJson upload(ModelMap modelMap, HttpServletRequest request, String type, @Value("${upload.path}")String path) throws IOException {
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            FileOutputStream outputStream = null;
            InputStream inputStream = null;
            try {
                //年月日
                String real = path + "/images/" + type + File.separator;
                File realfile = new File(real);
                //创建目录
                if(!realfile.exists()){
                    realfile.mkdirs();
                }
                //存储名称ID
                String id = UUID.randomUUID().toString().replaceAll("-","");
                String from_file_name = file.getOriginalFilename();
                String ext = FilenameUtils.getExtension(from_file_name);
                File save_File = new File(realfile,id+"."+ext);
                //保存到新文件中
                inputStream = file.getInputStream();
                outputStream = new FileOutputStream(save_File);
                FileCopyUtils.copy(inputStream,outputStream);
                Map<String,Object> map = new HashMap<>();
                map.put("filepath",realfile+"/"+id+"."+ext);
                j.setAttributes(map);
            } catch (Exception e) {
                j.setSuccess(false);
            }finally{
                if(outputStream!=null){
                    outputStream.close();
                }
                if(inputStream!=null){
                    inputStream.close();
                }

            }
        }
        return j;
    }

    @RequestMapping("/showImg")
    public void showImg(HttpServletRequest request, HttpServletResponse response, @RequestBody InitialQrManage initialQrManage) throws Exception {
        if(StringUtils.isEmpty(initialQrManage.getImgPath())){
            return;
        }
        byte[] data = null;
        File file = new File(initialQrManage.getImgPath());
        FileInputStream fileInputStream = new FileInputStream(file);
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        data = new byte[fileInputStream.available()];
        fileInputStream.read(data);
        fileInputStream.close();
        response.getWriter().write(encoder.encode(data));
    }
}
